<template>
    <div class="fillcontain">
        <head-top></head-top>
        <div class="table_container">
            <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                @expand='expand'
                :expand-row-keys='expendRow'
                :row-key="row => row.index"
                style="width: 100%">
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="设备 ID">
                          <span>{{ props.row.equip_id }}</span>
                        </el-form-item>
                      <el-form-item label="设备名称">
                        <span>{{ props.row.equip_name }}</span>
                      </el-form-item>
                      <el-form-item label="设备价格">
                        <span>{{ props.row.equip_price }}</span>
                      </el-form-item>
                      <el-form-item label="设备介绍">
                        <span>{{ props.row.equip_introduce }}</span>
                      </el-form-item>
                      <!-- <el-form-item label="是否启用">
                          <span v-show="props.row.is_del==1" size="small">禁用状态</span>
                          <span v-show="props.row.is_del==0" size="small">启用状态</span>
                      </el-form-item> -->

                      <el-form-item label="设备创建人">
                          <span>{{ props.row.created_user }}</span>
                      </el-form-item>
                      <el-form-item label="设备更新人">
                          <span>{{ props.row.update_user }}</span>
                      </el-form-item>
                      <el-form-item label="设备图片">
                          <img src="" style="width: 100px; height: 100px" :src="$host+props.row.equip_img"> >
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column
                  label="设备名称"
                  prop="equip_name">
                </el-table-column>
                <el-table-column
                  label="设备介绍"
                  prop="equip_introduce">
                </el-table-column>
                <el-table-column
                  label="设备销量"
                  prop="month_sale">
                  {{Math.round(Math.random()*100)}}
                </el-table-column>
               <!-- <el-table-column
                    label="状态"
                    prop="is_del">
                    <template scope="scope">
                        {{ scope.row.is_del | toAdmin }}
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button
                      size="mini"
                      type="Success"
                      @click="addEquip(scope.$index, scope.row)">添加设备</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="currentPage"
                            :page-sizes="[5, 10, 20, 40]"
                            :page-size="pagesize"
                            layout="total, sizes,prev, pager, next"
                            :total="tableData.length"
                            prev-text="上一页"
                            next-text="下一页">
                        </el-pagination>
                    </div>
            <el-dialog title="修改设备信息" v-model="dialogFormVisible">
                <el-form :model="selectTable">
                    <el-form-item label="设备名称" label-width="100px">
                        <el-input v-model="selectTable.equip_name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="设备介绍" label-width="100px">
                        <el-input v-model="selectTable.equip_introduce" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="设备库存" label-width="100px">
                        <el-input v-model="selectTable.equip_inventory"></el-input>
                    </el-form-item>
                    <el-form-item label="设备价格" label-width="100px">
                        <el-input v-model="selectTable.equip_price"></el-input>
                    </el-form-item>
                   <!-- <el-form-item label="是否启用" label-width="100px">
                        <el-button type="warning" v-show="selectTable.is_del==1" @click="changeOpen()">禁用状态</el-button>
                        <el-button type="success" v-show="selectTable.is_del==0" @click="changeOpen()">启用状态</el-button>
                    </el-form-item> -->
                   <el-form-item label="设备图片" label-width="100px">
                       <p>{{selectTable.equip_img}}</p>
                       <el-upload
                           class="upload-demo"
                           :action=posterURI
                           :headers="headers"
                           :on-preview="handlePreview"
                           :on-success="handleSuccess"
                           :on-remove="handleRemove"
                           :file-list="fileList"
                           list-type="picture">
                           <el-button size="small" type="primary">点击上传</el-button>
                           <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                       </el-upload>

                   </el-form-item>

                    <el-form-item label="设备图片" label-width="100px">
                        <el-upload
                          class="avatar-uploader"
                          :action="baseUrl + '/v1/addimg/shop'"
                          :show-file-list="false"
                          :on-success="handleServiceAvatarScucess"
                          :before-upload="beforeAvatarUpload">
                          <img v-if="selectTable.image_path" :src="baseImgPath + selectTable.image_path" class="avatar">
                          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateEquip">确 定</el-button>
              </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import headTop from '../components/headTop'
    import {baseUrl, baseImgPath} from '@/config/env'
    import {getEquips, getEquipsCount, getMenu, updateEquip, deleteEquip, getResturantDetail, getMenuById} from '@/api/getData'
    export default {
        data(){
            return {
                posterURI:this.$host+"/zk/uploadFileServer/uploadFolder",
                selectValue: "",
                baseUrl,
                baseImgPath,
                restaurant_id: null,
                city: {},
                offset: 0,
                limit: 3,
                count: 0,
                tableData: [],
                currentPage: 1, //默认显示页面为1
                pagesize: 5, //    每页的数据条数
                selectTable: {},
                dialogFormVisible: false,
                menuOptions: [],
                selectMenu: {},
                selectIndex: null,
                specsForm: {
		          	specs: '',
		          	packing_fee: 0,
		          	price: 20,
		        },
                specsFormrules: {
		        	specs: [
						{ required: true, message: '请输入规格', trigger: 'blur' },
					],
		        },
                fileList: [],
		        specsFormVisible: false,
                expendRow: [],
            }
        },
        created(){
        	this.restaurant_id = this.$route.query.restaurant_id;
            this.initData();
        },
        computed: {
            headers() {
                return{
                    "Authorization": localStorage.getItem('token')
                }
            },

        	specs: function (){
        		let specs = [];
        		if (this.selectTable.specEquips) {
	        		this.selectTable.specEquips.forEach(item => {
	        			specs.push({
	        				specs: item.specs_name,
	        				packing_fee: item.packing_fee,
	        				price: item.price,
	        			})
	        		})
        		}
        		return specs
        	}
        },
    	components: {
    		headTop,
    	},
        filters: {
            toAdmin(value){
                if(value==0)
                {
                    value="启用状态"
                }
                else if(value==1)
                {
                    value="禁用状态"
                }
                return value;

            },
            limitWord(value) {
                if (!value) {
                    value = "";
                } else if (value.length > 10) {
                    value = value.slice(0, 10) + "...";
                }
                return value + "...";


            }

        },

        methods: {
            handleSuccess(res){
                this.selectTable.equip_img = res.data;
                console.log(res.data)

            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file,) {
                console.log(file);
            },
            // changeOpen(){
            //     if(this.selectTable.is_del!=null)
            //     {
            //         if(this.selectTable.is_del==0)
            //         {
            //             this.selectTable.is_del=1;
            //         }
            //         else{
            //             this.selectTable.is_del = 0;
            //         }

            //     }


            // },
            async handleDelete(index, row) {
                alert("确定删除嘛？")
                var that =this;
                this.$axios({
                    method:'DELETE',
                    url: that.$host2+"/zk/all-equipment/"+row.equip_id,
                    headers:{
                        "Authorization": localStorage.getItem('token')
                    },
                }).then(res=>{
                    if(res.data.code==200){
                        that.$message.success("删除产品成功")
                        that.getEquips();


                    }else{

                        that.$message.error("删除产品失败，请稍后重试")

                    }

                }).catch(error=>{
                    that.$message.error("删除产品失败，请稍后重试")



                })
            },
            addEquip(index, row){
                this.$router.push({ path: 'addEquip', query: { restaurant_id: row.id }})
            },
            async initData(){
                console.log("我进来了====》》》");
                this.getEquips();

                try{
                    const countData = await getEquipsCount({restaurant_id: this.restaurant_id});
                    if (countData.status == 1) {
                        this.count = countData.count;
                    }else{
                        throw new Error('获取数据失败');
                    }

                }catch(err){
                    console.log('获取数据失败', err);
                }
            },
            async getMenu(){
            	this.menuOptions = [];
                try{
                    const menu = await getMenu({restaurant_id: this.selectTable.restaurant_id, allMenu: true});
                    menu.forEach((item, index) => {
                        this.menuOptions.push({
                        	label: item.name,
                        	value: item.id,
                        	index,
                        })
                    })
                }catch(err){
                    console.log('获取商品失败', err);
                }
            },
            async getEquips(){
                var that = this
                    this.$axios.get(this.$host2+"/zk/all-equipment/page/"+this.offset+"/"+this.limit,{
                        headers: {
                            "Authorization": localStorage.getItem('token')

                        }
                    }).then(
                        res=>{
                            that.tableData = res.data.records;
                            console.log(that.tableData)


                        }
                    ).catch(error=>console.log(error));

            },
            tableRowClassName(row, index) {
		        if (index === 1) {
		        	return 'info-row';
		        } else if (index === 3) {
		        	return 'positive-row';
		        }
		        return '';
		    },
		    addspecs(){
				this.specs.push({...this.specsForm});
				this.specsForm.specs = '';
				this.specsForm.packing_fee = 0;
				this.specsForm.price = 20;
				this.specsFormVisible = false;
			},
			deleteSpecs(index){
				this.specs.splice(index, 1);
			},
             //每页下拉显示数据
                        handleSizeChange: function(size) {
                            this.pagesize = size;
                            /*console.log(this.pagesize) */
                        },
                        //点击第几页
                        handleCurrentChange: function(currentPage) {
                            this.currentPage = currentPage;
                            /*console.log(this.currentPage) */
                        },
            expand(row, status){
            	if (status) {
            		this.getSelectItemData(row)
            	}else{
                    const index = this.expendRow.indexOf(row.index);
                    this.expendRow.splice(index, 1)
                }
            },
            handleEdit(row) {
                console.log(row.equip_id)
            	this.getSelectItemData(row, 'edit')
                this.dialogFormVisible = true;
                this.selectTable =JSON.parse(JSON.stringify(row));
                console.log(this.selectTable)
            },
            async getSelectItemData(row, type){

                this.selectTable = {...row, ...{restaurant_name: restaurant.name, restaurant_address: restaurant.address, category_name: category.name}};

                this.selectMenu = {label: category.name, value: row.category_id}
                this.tableData.splice(row.index, 1, {...this.selectTable});
                this.$nextTick(() => {
                    this.expendRow.push(row.index);
                })

            },
            handleSelect(index){
            	this.selectIndex = index;
            	this.selectMenu = this.menuOptions[index];
            },
            handleServiceAvatarScucess(res, file) {
                if (res.status == 1) {
                    this.selectTable.image_path = res.image_path;
                }else{
                    this.$message.error('上传图片失败！');
                }
            },
            beforeAvatarUpload(file) {
                const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isRightType) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isRightType && isLt2M;
            },
            async updateEquip(){
                this.dialogFormVisible = false;
                try{
                    this.$axios({
                        method: 'put',
                        url: this.$host2+`/zk/all-equipment/`,
                        headers:{
                            "Authorization": localStorage.getItem('token')
                        },
                        params: {
                            equipId: this.selectTable.equip_id,
                            equipName: this.selectTable.equip_name,
                            equipImg: this.selectTable.equip_img,
                            equipIntroduce: this.selectTable.equip_introduce,
                            equipPrice: this.selectTable.equip_price,
                            // isDel: this.selectTable.is_del,
                            equipInventory: this.selectTable.equip_inventory,
                            updateUser: "金宇轩"

                        },}).then(res=>{
                            if(res.data.code==200){
                                this.$message({
                                    type: 'success',
                                    message: '更新成功'
                                });
                                this.getEquips();
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: res.data.msg
                                });
                            }
                    }).catch(error=>{
                        console.log(error)
                        this.$message({
                            type: 'error',
                            message: res.data.msg
                        });
                    });

                }catch(err){
                    console.log('更新套餐信息失败', err);
                }
            },
        },
    }
</script>

<style lang="less">
	@import '../style/mixin';
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .table_container{
        padding: 20px;
    }
    .Pagination{
        display: flex;
        justify-content: flex-start;
        margin-top: 8px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }
    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }
</style>
